package com.jajahome.feature;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jajahome.R;
import com.jajahome.feature.diy.DiyDetailAct;
import com.jajahome.util.StringUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CameraAct extends AppCompatActivity {
    private ImageView ivCamera;
    private SurfaceView mSurface;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private FrameLayout flay_view;
    private SeekBar seekbar;
    private TextView text;
    private boolean previewRunning = true;
    //preview是否是活动的。防止preview是inactive时去调用对焦产生异常。
    private boolean isPreviewActive = true;
    private String img_url;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private ImageView iv_reference_line, iv_open;
    private boolean ISOFF = true;
    private int autoFocus = 0;
    private String mCategory;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.act_camera);
        init();
    }

    private void init() {
        img_url = getIntent().getStringExtra("imgurl");
        mCategory = getIntent().getStringExtra(DiyDetailAct.DIY_CATEGORY);
        ivCamera = (ImageView) findViewById(R.id.iv_camera);
        mSurface = (SurfaceView) findViewById(R.id.surface);
        flay_view = (FrameLayout) findViewById(R.id.flay_view);
        iv_reference_line = (ImageView) findViewById(R.id.iv_reference_line);
        iv_open = (ImageView) findViewById(R.id.iv_open);
        text = (TextView) findViewById(R.id.text);
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        mHolder = mSurface.getHolder();


        mHolder.addCallback(new MySurfaceViewCallback());
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHolder.setFixedSize(500, 500);
        ivCamera.setOnClickListener(new OnClickListenerImpl());
        imageLoader.loadImage(img_url, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
//                touchImageView.setBitmap(lo adedImage);
//                Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.mipmap.icon_test2)).getBitmap();
//                Matrix matrix = new Matrix();
//                matrix.setRotate(90);
//                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            }
        });
        iv_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ISOFF) {
                    ISOFF = false;
                    Camera.Parameters mParameters;
                    mParameters = mCamera.getParameters();
                    mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                    mCamera.setParameters(mParameters);
                } else {
                    ISOFF = true;
                    Camera.Parameters mParameters;
                    mParameters = mCamera.getParameters();
                    mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    mCamera.setParameters(mParameters);
//                    mCamera.release();
                }
            }
        });
        seekbar.setOnSeekBarChangeListener(onZoomChangeListener);
    }

    private SeekBar.OnSeekBarChangeListener onZoomChangeListener = new SeekBar.OnSeekBarChangeListener() {

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // TODO Auto-generated method stub
            int progress1 = progress / 10;
            Log.e("progress1", progress1 + "！！！" + progress);
            Camera.Parameters p = mCamera.getParameters();
            p.setZoom(progress1);
            mCamera.setParameters(p);
        }

    };

    private class MySurfaceViewCallback implements SurfaceHolder.Callback {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                if (mCamera != null) {
                    // 停掉原来摄像头的预览
                    mCamera.stopPreview();
                    // 释放资源
                    mCamera.release();
                    // 取消原来摄像头
                    mCamera = null;
                }
                mCamera = Camera.open(0);

            } catch (Exception e) {
                Toast.makeText(CameraAct.this, "摄像头打开失败,请开启拍照权限", Toast.LENGTH_LONG).show();
                finish();
                return;
            }
            mCamera = deal2(mCamera);

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mCamera != null) {
                if (previewRunning) {
                    mCamera.stopPreview();
                    previewRunning = false;
                }
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
    }


    private Camera deal2(Camera camera) {
        // 设置camera预览的角度，因为默认图片是倾斜90度的
        // camera.setDisplayOrientation(90);
        autoFocus = 0;
        int previewWidth = 0;
        int previewHeight = 0;
        // 获取窗口的管理器
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 获得窗口里面的屏幕
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        Camera.Parameters parameters = camera.getParameters();
//         parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); //开启闪光灯,支持
        setDispaly(parameters, mCamera);
        // parameters.setRotation(90);
//         parameters.setPreviewFrameRate(3);// 每秒3帧 每秒从摄像头里面获得3个画面,
        // 某些机型（红米note2）不支持
        parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片输出的格式
        parameters.set("jpeg-quality", 100);// 设置照片质量
        try {
            // 选择合适的预览尺寸
            List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();
            List<Camera.Size> imgSizeList = parameters.getSupportedPictureSizes();
//            text.setText(new Gson().toJson(sizeList) + "\n" + new Gson().toJson(imgSizeList));
            // 如果sizeList只有一个我们也没有必要做什么了，因为就他一个别无选择
            if (sizeList.size() > 1) {
                Iterator<Camera.Size> itor = sizeList.iterator();
                while (itor.hasNext()) {
                    Camera.Size cur = itor.next();
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后2位
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) cur.height / (float) cur.width);
                    String proportion = numberFormat.format((float) 3 / (float) 4);
                    if (result.equals(proportion)) {//4:3
                        if (cur.width <= height && cur.height <= width) {//相机预览大小比手机屏幕要小
                            if (cur.width >= previewWidth && cur.height >= previewHeight) {
                                previewWidth = cur.width;//1440
                                previewHeight = cur.height;//1080
                                break;
                            }
                        }
                    }
                }
            }


            int pictureWidth = 0;
            int pictureHeight = 0;
            if (imgSizeList.size() > 1) {
                Iterator<Camera.Size> itor = imgSizeList.iterator();
                while (itor.hasNext()) {
                    Camera.Size cur = itor.next();
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后2位
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) cur.height / (float) cur.width);
                    String proportion = numberFormat.format((float) 3 / (float) 4);
                    if (result.equals(proportion)) {
                        if (cur.width <= previewWidth && cur.height <= previewHeight) {
                            pictureWidth = cur.width;
                            pictureHeight = cur.height;
                            break;
                        }
                    }
                }
            }

            int fw = 0;
            int fh = 0;
            if (previewHeight < width && width >= 1080) {
                //手机屏幕大于1080*1920，但没有支持的分辨率，放大到1080*1440，就是4：3的屏640 480  1920 1080
                NumberFormat numberFormat1 = NumberFormat.getInstance();
                // 设置精确到小数点后2位
                numberFormat1.setMaximumFractionDigits(3);
                float f = Float.valueOf(numberFormat1.format((float) width / previewHeight));
                float pw = f * Float.valueOf(numberFormat1.format((float) previewWidth));
                fw = (int) pw;
                fh = width;
            } else {
                fw = previewWidth;
                fh = previewHeight;
            }
            RelativeLayout.LayoutParams layoutParams =
                    new RelativeLayout.LayoutParams(fh, fw);
//            mSurface.setLayoutParams(layoutParams);
            flay_view.setLayoutParams(layoutParams);
            int sources = getImage();
            if (sources != 0) {
                Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(sources)).getBitmap();
                Matrix matrix = new Matrix();
                matrix.setRotate(90);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            iv_reference_line.setImageBitmap(bitmap);
            }
            parameters.setPreviewSize(previewWidth, previewHeight); // 获得摄像区域的大小
            parameters.setPictureSize(pictureWidth, pictureHeight); // 获得保存图片的大小  w 1024  h 768  4:3
            camera.setPreviewDisplay(mHolder);
            camera.setParameters(parameters);// 把上面的设置 赋给摄像头
            camera.startPreview();// 开始预览
//            camera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上
            camera.autoFocus(new AutoFocusCallbackImpl());
            previewRunning = true;
        } catch (Exception e) {
            Log.e("CameraAct", e.toString());
        }
        return camera;
    }

    private int getImage() {
        if (StringUtil.isEmpty(mCategory)){
            return 0;
        }
        if (mCategory.equals("卧室")) {
            return R.mipmap.icon_zhuwo;
        } else if (mCategory.equals("书房")) {
            return R.mipmap.icon_shufang;
        } else if (mCategory.equals("餐厅")) {
            return R.mipmap.icon_caiting;
        } else if (mCategory.equals("客厅")) {
            return R.mipmap.icon_keting;
        } else if (mCategory.equals("次卧")) {
            return R.mipmap.icon_ciwo;
        }
        return 0;
    }

    // 控制图像的正确显示方向
    private void setDispaly(Camera.Parameters parameters, Camera camera) {
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            setDisplayOrientation(camera, 90);
        } else {
            parameters.setRotation(90);
        }
    }

    // 实现的图像的正确显示
    private void setDisplayOrientation(Camera camera, int i) {
        Method downPolymorphic;
        try {
            downPolymorphic = camera.getClass().getMethod(
                    "setDisplayOrientation", new Class[]{int.class});
            if (downPolymorphic != null) {
                downPolymorphic.invoke(camera, new Object[]{i});
            }
        } catch (Exception e) {
            Log.e("Came_e", "图像出错");
        }
    }

    private class OnClickListenerImpl implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (mCamera != null) {
                autoFocus = 1;
                mCamera.autoFocus(new AutoFocusCallbackImpl());
            }
        }
    }

    private class AutoFocusCallbackImpl implements Camera.AutoFocusCallback {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            //成功
            if (success) {
                if (autoFocus == 1) {
                    mCamera.takePicture(sc, pc, jpgcall);
                }
            }
        }
    }


    private Camera.ShutterCallback sc = new Camera.ShutterCallback() {
        @Override
        public void onShutter() {
            //按下快门之后进行的操作
        }
    };

    private Camera.PictureCallback pc = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

        }
    };
    private Camera.PictureCallback jpgcall = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // 保存图片的操作
            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
            iv_reference_line.setDrawingCacheEnabled(true);
            String fileName = "jajahome_" + System.currentTimeMillis() + ".jpg";
            String sdCardDir = Environment.getExternalStorageDirectory() + "/com.jaja.home/image";//获取SDCard目录com.jaja.home
            String filePath = sdCardDir
                    + File.separator
                    + fileName;
            bmp = rotateBitmapByDegree(bmp, 0);//View代表方法传入的控件
            save(bmp, filePath, fileName, true);
//            bmp = loadBitmap(filePath, true);
//            setPictureDegreeZero(filePath);
//            iv_reference_line.CreatNewPhoto();
//            Bitmap bmp2 = iv_reference_line.getDrawingCache();
//            Bitmap bmp3 = combineBitmap(bmp, bmp2, iv_reference_line.getMatrix());
//            save(bmp3, filePath, fileName, true);
            mCamera.stopPreview();
            mCamera.startPreview();
            iv_reference_line.setDrawingCacheEnabled(false);
        }
    };

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private void save(Bitmap bitmap, String filePath, String fileName, boolean isShow) {
        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs(); // 创建文件夹
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); // 向缓冲区之中压缩图片
            bos.flush();
            bos.close();
            if (isShow) {
//                Toast.makeText(CameraAct.this,
//                        "拍照成功，照片已保存在" + fileName + "文件之中！", Toast.LENGTH_SHORT)
//                        .show();
                Intent intent = new Intent();
                ArrayList<String> img = new ArrayList<>();
                img.add(filePath);
                intent.putExtra("data", img);
                setResult(RESULT_OK, intent);
                finish();
            }
        } catch (Exception e) {
            Toast.makeText(CameraAct.this, "拍照失败！", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 从给定的路径加载图片，并指定是否自动旋转方向
     */
    public Bitmap loadBitmap(String imgpath, boolean adjustOritation) {
        if (!adjustOritation) {
            return BitmapFactory.decodeFile(imgpath);// 从给定路径加载图片
        } else {
            Bitmap bm = BitmapFactory.decodeFile(imgpath);
            int digree = 0;
            ExifInterface exif = null;
            try {
                exif = new ExifInterface(imgpath);
            } catch (IOException e) {
                e.printStackTrace();
                exif = null;
            }
            if (exif != null) {
                // 读取图片中相机方向信息
                // int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                // ExifInterface.ORIENTATION_NORMAL);
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_FLIP_VERTICAL);
                // 计算旋转角度
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                    default:
                        digree = 0;
                        break;
                }
            }
            if (digree != 0) {
                // 旋转图片
                Matrix m = new Matrix();
                m.postRotate(digree);
                bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
            }
            return bm;
        }
    }

    /**
     * 将图片的旋转角度置为0  ，此方法可以解决某些机型拍照后图像，出现了旋转情况
     *
     * @param path
     * @return void
     */
    private void setPictureDegreeZero(String path) {
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            // 修正图片的旋转角度，设置其不旋转。这里也可以设置其旋转的角度，可以传值过去，
            // 例如旋转90度，传值ExifInterface.ORIENTATION_ROTATE_90，需要将这个值转换为String类型的
            exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "no");
            exifInterface.saveAttributes();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground, Matrix matrix) {
        if (background == null) {
            return null;
        }
        int bgWidth = foreground.getHeight();
        int bgHeight = foreground.getWidth();
        Log.e("WH", bgWidth + "!!" + bgHeight + "!");
        Bitmap newmap = Bitmap.createBitmap(bgHeight, bgWidth, Bitmap.Config.ARGB_8888);
//        newmap = Bitmap.createBitmap(newmap,720,960,bgHeight,bgWidth);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(background, 0, 0, null);
//        canvas.drawBitmap(background, matrix, null);
        canvas.save();
        canvas.restore();
        return newmap;
    }
}
